package cn.lingyangwl.agile.common.core.utils;

import cn.lingyangwl.framework.core.response.Resp;
import cn.lingyangwl.agile.common.core.exception.enums.GlobalErrorEnum;
import com.alibaba.fastjson2.JSON;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author shenguangyang
 */
public class WebFluxUtils {
    /**
     * 设置webflux模型响应
     *
     * @param response ServerHttpResponse
     * @param value    响应内容
     * @return Mono<Void>
     */
    public static Mono<Void> writeFail(ServerWebExchange exchange, Object value) {
        return writer(exchange, HttpStatus.OK, value, GlobalErrorEnum.FAIL.getCode());
    }

    /**
     * 设置webflux模型响应
     * @return Mono<Void>
     */
    public static Mono<Void> writeFail(ServerWebExchange exchange, HttpStatus httpStatus,  Object value) {
        return writer(exchange, httpStatus, value, GlobalErrorEnum.FAIL.getCode());
    }

    /**
     * 设置webflux模型响应
     *
     * @param response ServerHttpResponse
     * @param code     响应状态码
     * @param value    响应内容
     * @return Mono<Void>
     */
    public static Mono<Void> writer(ServerWebExchange exchange, Object value, int code) {
        return writer(exchange, HttpStatus.OK, value, code);
    }

    /**
     * 设置webflux模型响应
     *
     * @param response ServerHttpResponse
     * @param status   http状态码
     * @param code     响应状态码
     * @param value    响应内容
     * @return Mono<Void>
     */
    public static Mono<Void> writer(ServerWebExchange exchange, HttpStatus status, Object value, int code) {
        return writer(exchange, MediaType.APPLICATION_JSON_VALUE, status, value, code);
    }

    /**
     * 设置webflux模型响应
     *
     * @param response    ServerHttpResponse
     * @param contentType content-type
     * @param status      http状态码
     * @param code        响应状态码
     * @param value       响应内容
     * @return Mono<Void>
     */
    public static Mono<Void> writer(ServerWebExchange exchange,
                                                   String contentType, HttpStatus status, Object value, int code) {

        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
        DataBuffer dataBuffer = response.bufferFactory()
                .wrap(JSON.toJSONString(Resp.fail(code, value.toString()).wrapReactive(request.getHeaders())).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
}
